import logging
import os
import simplejson
import progressbar
import csv
import tempfile
import itertools
from lxml import etree


def get_progressbar(maxvalue):
  widgets = [progressbar.Percentage(), progressbar.Bar()]
  return progressbar.ProgressBar(widgets=widgets, maxval=maxvalue).start()


def grouper(n, iterable, fillvalue=None):
  #grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
  args = [iter(iterable)] * n
  return itertools.izip_longest(fillvalue=fillvalue, *args)


def _get_filepath(filename,path=None):
  if path:
    return os.path.join(path,filename)
  else:
    return filename


def join_path(subdirectory,root_directory):
  return os.path.join(root_directory,subdirectory)


def create_dir(directory,path=None):
  joined_path = _get_filepath(directory,path)
  if not os.path.exists(joined_path):
    logging.info('Creating not existing directory %s',
      joined_path)
    os.makedirs(joined_path)

################ JSON ########################################################
def load_json(filename,inputdir=None):
  fullname = _get_filepath(filename,inputdir)
  return simplejson.load(open(fullname,'r'))

def write_json(json_data,filename,outputdir=None,indent=0,sort_keys=False):
    fullname = _get_filepath(filename,outputdir)
    logging.info('Writing results to %s ',fullname)
    save = open(fullname, 'w')
    save.write(simplejson.dumps(json_data,sort_keys=sort_keys,indent=indent))
    save.flush()
    save.close()


################ CSV #########################################################
#rows is a list of list of rows
def write_CSV(rows,filename,outputdir=None):
  fullname = _get_filepath(filename,outputdir)
  logging.info('Writing results to %s ', fullname)
  save = open(fullname, 'w')
  writer = csv.writer(save)
  writer.writerows(rows)
  save.close()


def load_CSV(filename,inputdir=None):
  fullname = _get_filepath(filename,inputdir)
  logging.info('Loading rows from %s ', fullname)
  csv_file = open(filename, 'rU')
  reader = csv.reader(csv_file)
  rows = [row for row in reader]
  csv_file.close()
  return rows


################ XML #########################################################
def load_xml_root(filename,inputdir=None):
  fullname = _get_filepath(filename,inputdir)
  logging.info('Loading xml tree from %s ', fullname)
  return etree.parse(loadable_file).getroot()


################ Plain #######################################################
def write_file(content,filename,outputdir=None):
  fullname = _get_filepath(filename,outputdir)
  logging.info('Writing results to %s ', fullname)
  save = open(results_file, 'w')
  save.write(content)
  save.flush()
  save.close()


def load_file(filename,inputdir=None):
  fullname = _get_filepath(filename,inputdir)
  logging.info('Loading data from %s ', filename)
  return open(loadable_file, 'r')


################ Temp Files ##################################################
def write_temp_file(content):
  filename = tempfile.NamedTemporaryFile()
  filename.write(content)
  filename.flush()
  return filename


def get_temp_file():
  return tempfile.NamedTemporaryFile()
